import {Component, ElementRef, OnInit, QueryList, ViewChild, ViewChildren} from '@angular/core';
import {AdOssUploadService} from "../../../lib/service/ad-oss-upload.service";
import {NzMessageService} from "ng-zorro-antd";
import {BannerService} from "../../banner/banner.service";
import {CategoryService} from "../../category/category.service";
import {ActivatedRoute, Router} from "@angular/router";
import {adSystemApiUrl, AliyunOssOutputUrl, tuikeSystemUrl} from "../../../../config/api";
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";
import * as moment from "moment";
import {EditorComponent} from "../../../comm-components/wangeditor";
import {HttpService} from "../../../lib/service/http.service";

@Component({
  selector: 'app-add-activity',
  templateUrl: './add-activity.component.html',
  styleUrls: ['./add-activity.component.scss'],
  providers: [BannerService, CategoryService]
})
export class AddActivityComponent implements OnInit {
  validateForm: FormGroup;
  validateForm1: FormGroup;
  validateSendForm: FormGroup;
  activity_type;
  active_type;
  fileList = [];
  picList = [];
  task_ids = [];
  GoodsModalVisible = false;
  taskPage = 1;
  taskPageSize = 5;
  taskList = [];
  taskTotal = 0;
  submitStatus = false;
  isShow = false;
  type: string;
  message: string;
  editId = null;
  isChange = false;
  canChange = false;
  categoryList = [];
  page = null;
  start_date = null;
  end_date = null;
  editStatus = false;
  task_name = '';
  selectedGroup = null;
  typeList = [];
  isConfirmGoodsLoading = false;
  picSizeInfo = '上传数量限制1张,尺寸建议为702*380';
  description = '';
  checkedGoodsInfo = [];
  begin_time;
  end_time;
  show_time;
  GoodsModalContent;
  active_page;
  categoryList1: Array<any> = [];
  card_disabled: boolean = false;
  editors = [{'content': '', 'checkedGoodsInfo': [], 'descError': false}];
  operateEditorIndex;
  editIndex;
  @ViewChild(EditorComponent) editor: EditorComponent;
  @ViewChildren(EditorComponent)
  editorlist: QueryList<EditorComponent>;
  selectedCard;
  taskLoading = false;
  detail: boolean = false;

  constructor(
    private adOssUploadService: AdOssUploadService,
    private _message: NzMessageService,
    private bannerService: BannerService,
    private categoryService: CategoryService,
    private httpService: HttpService,
    private router: Router,
    private route: ActivatedRoute,
    private el: ElementRef,
    private fb: FormBuilder
  ) {
  }

  ngOnInit() {
    let params = this.route.snapshot.queryParams;
    this.activity_type = params['type'] ? +params['type'] : null;
    this.active_page = params['page'] ? +params['page'] : null;
    this.detail = !!params['detail'];
    console.log(this.detail);
    this.id = params['id'] ? params['id'] : null;
    this.fileList = ["pic"];

    this.validateForm = this.fb.group({
      title: ["", [Validators.required]],
      validity_end: [null, [Validators.required]],
      validity_start: [null, [Validators.required]],
      pic_url: [["pic"], [Validators.required, this.confirmationValidator]],
      status: [1, [Validators.required]],
      is_top: [0, [Validators.required]]
    });

    let validateForm = this.validateForm;

    if (this.activity_type == 5) {
      validateForm.addControl('show_at', this.fb.control(null, [Validators.required]));
    } else if (this.activity_type == 3 && !validateForm.controls['user_num_limit']) {
      // this.getCardList();
      validateForm.addControl('show_at', this.fb.control(null, [Validators.required]));
      validateForm.addControl('user_num_limit', this.fb.control(null, [Validators.required, Validators.pattern('^[0-9]+$')]));
      validateForm.addControl('card_coupons_uuid', this.fb.control(null, [Validators.required]));
    } else if (this.activity_type == 4 && !validateForm.controls['category_id']) {
      this.getcategoryList1();
      validateForm.addControl('category_id', this.fb.control(null, [Validators.required]));
    } else if (this.activity_type != 3 && this.activity_type != 4) {
      validateForm.removeControl('user_num_limit');
      validateForm.removeControl('card_coupons_uuid');
      validateForm.removeControl('category_id');
    }

    if (this.id) {
      this.getDetail(this.id, (res) => {
        if (res.code === 200) {
          this.editors = [];
          let data = res.data;
          // if (data.show_at == null || data.show_at.charAt(0) == '0') {
          //   data.show_at = '2018-01-01 00:00:00';
          // };
          let json = {
            is_top: data.is_top,
            title: data.title,
            pic_url: [{url: data.pic_url, src: AliyunOssOutputUrl + data.pic_url}],
            validity_start: new Date(data.validity_start),
            validity_end: new Date(data.validity_end),
            show_at: new Date(data.show_at),
            user_num_limit: data.user_num_limit,
            card_coupons_uuid: data.card_coupons_uuid,
            category_id: data.category_id,
            content: data.content,
            status: data.status
          };
          this.fileList = [{url: data.pic_url, src: AliyunOssOutputUrl + data.pic_url}];
          if (data.type != 3) {
            delete json.user_num_limit;
            delete json.card_coupons_uuid;
          }
          if (data.type != 4) {
            delete json.category_id;
          }
          if (data.type != 3 && data.type != 5) {
            delete json.show_at
          }

          let start = moment(json['validity_start']).format('YYYY:MM:DD HH:mm:ss');
          let end = moment(json['validity_end']).format('YYYY:MM:DD HH:mm:ss');
          let editors = data.content.indexOf('[') == 0 ? JSON.parse(data.content) : '';
          if (editors) {
            editors.map((e, i) => {
              this.editors.push({'content': e.content, 'checkedGoodsInfo': [], 'descError': false});
            });

            setTimeout(() => {
              this.editors.map((e, i) => {
                this.editorlist['_results'][i].loadingHandle(editors[i]['content']);
              });
            }, 200);
            let validity:any = '';
            if (!this.detail) {
              validity = {
                'validity_start': start,
                'validity_end': end
              };
            }
            editors.map((e, i) => {
              let activity_type = null;
              this.activity_type != 5 ? activity_type = 1 : activity_type = 2;
              this.bannerService.getTaskList(1, 666, activity_type, validity, this.task_name).subscribe(res => {
                if (res.code == 200) {
                  let taskList = res.data.list.data;
                  taskList.map((e1, i1) => {
                    e1['taskPreview'] = `${AliyunOssOutputUrl}/${e1['task_content']['image']}?update=${new Date().getTime()}`;
                    e['link_task'].split(',').map((e2, i2) => {
                      if (e1.id == e2) {
                        this.editors[i]['checkedGoodsInfo'].push(e1);
                      }
                    })
                  });
                }
              });
            });
          } else {
            this.editors.push({'content': data.content, 'checkedGoodsInfo': [], 'descError': false});
            setTimeout(() => {
              this.editorlist['_results'][0].loadingHandle(data.content);
            }, 200);
          }
          validateForm.patchValue(json);
          if (this.activity_type == 3) {
            this.getCardList(true);
          }
        }
      })
    }
  }

  showTime(e) {
    if (this.editors.length > 0) {
      this.editors.map((e, i) => {
        e['checkedGoodsInfo'] = [];
      })
    }
    if (this.cardList.length > 0) {
      this.cardList = [];
      this.validateForm.controls['card_coupons_uuid'].patchValue(null);
    }
  }


  picError = false;
  nameError = false;
  commentError = false;
  nameRequired = false;
  commentRequired = false;
  sortRequired = false;
  taskRequired = false;

  deleteEditor(i) {
    this.editors.splice(i, 1);
  }

  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value || !control.value[0]) {
      return {required: true};
    } else if (control.value[0] == "pic") {
      return {required: true, error: true};
    }
  };

  addEditor() {
    this.editors.push({'content': '', 'checkedGoodsInfo': [], 'descError': false});
  }

  fileChange(list) {
    setTimeout(_ => {
      this.validateForm.patchValue({
        pic_url: list
      });
      this.validateForm.controls['pic_url'].updateValueAndValidity();
      this.validateForm.controls['pic_url'].markAsDirty();
    });
    // this.uploadImg1();
  }

  picChange(where) {
    setTimeout(_ => {
      this.validateForm.controls['pic_url'].updateValueAndValidity();
      this.validateForm.controls['pic_url'].markAsDirty();
    });
  }

  newArray = (len) => {
    const result = [];
    for (let i = 0; i < len; i++) {
      result.push(i);
    }
    return result;
  };

  _startValueChange = () => {
    if (this.start_date > this.end_date) {
      this.end_date = null;
    }
  }

  _endValueChange = () => {
    if (this.start_date > this.end_date) {
      this.start_date = null;
    }
  }

  _disabledStartDate = (startValue) => {
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    const now_time = now.getTime();
    if (!startValue || !this.validateForm.value.validity_end) {
      return startValue < now_time;
    }
    return (startValue.getTime() >= this.validateForm.value.validity_end.getTime()) || (startValue.getTime() <= Date.now());
  }

  _disabledEndDate = (endValue) => {
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    const now_time = now.getTime();
    if (!endValue || !this.start_date) {
      return endValue.getTime() < now_time;
    }
    return endValue.getTime() < this.start_date.getTime();
  }

  get _isSameDay() {
    return this.start_date && this.end_date && moment(this.start_date).isSame(this.end_date, 'day');
  }

  get _endTime() {
    return {
      nzHideDisabledOptions: true,
      nzDisabledHours: () => {
        return this._isSameDay ? this.newArray(this.start_date.getHours()) : [];
      },
      nzDisabledMinutes: (h) => {
        if (this._isSameDay && h === this.start_date.getHours()) {
          return this.newArray(this.start_date.getMinutes());
        }
        return [];
      },
      nzDisabledSeconds: (h, m) => {
        if (this._isSameDay && h === this.start_date.getHours() && m === this.start_date.getMinutes()) {
          return this.newArray(this.start_date.getSeconds());
        }
        return [];
      }
    };
  }


  getFormControl(name) {
    return this.validateForm.controls[name];
  }

  WidthCheck(type, str, maxLen, e?) {
    var w = 0;
    var tempCount = 0;
    if (type == 'name') {
      if (e.length == 0) {
        this.nameRequired = true;
      } else {
        this.nameRequired = false;
      }
    } else {
      if (e.length == 0) {
        this.commentRequired = true;
      } else {
        this.commentRequired = false;
      }
    }

    for (var i = 0; i < str.length; i++) {
      var c = str.charCodeAt(i);
      if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
        w++;
      } else {
        w += 2;
      }

      if (w > maxLen) {
        // str = str.substr(0, i);
        if (type == 'name') {
          // this.el.nativeElement.querySelector('#activity_name').value = str;
          this.nameError = true;
        } else {
          // this.el.nativeElement.querySelector('#comment').value = str;
          this.commentError = true;
        }
      } else {
        if (type == 'name') {
          this.nameError = false;
        } else {
          this.commentError = false;
        }
      }
    }
  }

  search() {
    this.taskPage = 1;
    this.getTaskList();
  }

  reset() {
    this.task_name = '';
    this.taskPage = 1;
    this.getTaskList();
  }

  getDetail(id, call) {
    let url = `${tuikeSystemUrl}/api/v1/admin/activity_find/detail?id=` + id;
    this.id = id;
    this.httpService.httpGetAuth(url).subscribe(res => {
      if (typeof call == 'function') {
        call(res);
      }
    })
  }

  getTaskList() {
    let control = this.validateForm.controls;
    let start = moment(control['validity_start'].value).format('YYYY:MM:DD HH:mm:ss');
    let end = moment(control['validity_end'].value).format('YYYY:MM:DD HH:mm:ss');
    let activity_type = null;
    this.activity_type != 5 ? activity_type = 1 : activity_type = 2;
    this.taskLoading = true;
    this.bannerService.getTaskList(this.taskPage, this.taskPageSize, activity_type, {
      'validity_start': start,
      'validity_end': end
    }, this.task_name).subscribe(res => {
      if (res.code === 200) {
        let data = res.data;
        this.taskList = data.list.data;
        this.taskTotal = data.list.total;
        let task_type = data.task_type;
        for (let key in  task_type) {
          this.typeList.push({
            'label': task_type[key],
            'value': key
          })
        }
        ;
        this.taskList.map((e, i) => {
          e['taskPreview'] = `${AliyunOssOutputUrl}/${e['task_content']['image']}?update=${new Date().getTime()}`;
          e['checked'] = false;
          if (this.editors[this.editIndex]['checkedGoodsInfo'].length > 0) {
            this.editors[this.editIndex]['checkedGoodsInfo'].map((e1, i1) => {
              if (e.id == e1.id) {
                e['checked'] = true;
              }
            })
          }
        });
        this.taskLoading = false;
      }
    })
  }


  closeGoodsModal() {
    this.GoodsModalVisible = false;
    this.taskPage = 1;
    this.task_name = '';
  }


  addLinkGoods(e, index) {
    let control = this.validateForm.controls;
    if (!control['validity_start'].value || !control['validity_end'].value) {
      this._message.create('error', '请先选择开始时间以及结束时间');
      return;
    }
    e.stopPropagation();
    this.editIndex = index;
    this.GoodsModalVisible = true;
    this.getTaskList();
  }


  dealTask(e, data) {
    let editor = this.editors[this.editIndex];
    let checkedGoodsInfo = editor['checkedGoodsInfo'];
    this.taskList.map((item, i) => {
      if (item.id == data.id) {
        if (checkedGoodsInfo.length == 0) {
          if (e) {
            item['checked'] = true;
            checkedGoodsInfo.push(data);
          }
        } else {
          if (e) {
            let num = 0;
            checkedGoodsInfo.map((item1, i) => {
              if (item1.id != data.id && num === 0) {
                item['checked'] = true;
                checkedGoodsInfo.push(data);
                num++;
              }
              return;
            });
          } else {
            checkedGoodsInfo.map((item2, i) => {
              if (item2.id == data.id) {
                item['checked'] = false;
                checkedGoodsInfo.splice(i, 1);
                return;
              }
              return;
            });
          }
        }
      }
    });
  }

  PostData(event): void {
    // console.log(event);
  }

  id = '';

  getcategoryList1() {
    let url = `${tuikeSystemUrl}/api/v1/admin/activity_category_find/index?`;
    let json = {
      page: 1,
      pageSize: 100,
    };
    this.httpService.httpPostAuth(url, json).subscribe(res => {
      if (res.code === 200) {
        let data = res.data;
        this.categoryList1 = data.data;
      }
    });
  }

  saveDiscovery(json) {
    let url = `${tuikeSystemUrl}/api/v1/admin/activity_find/create?`;
    if (this.id) {
      url = `${tuikeSystemUrl}/api/v1/admin/activity_find/update?`;
      json.id = this.id;
    } else {
      delete json.id;
    }

    this.httpService.httpPostAuth(url, json).subscribe(res => {
      this.submitStatus = true;
      if (res.code === 200) {
        this._message.create('success', this.id ? '修改成功' : '添加成功');
        let params = {};
        this.active_page ? params['page'] = this.active_page : '';
        this.activity_type ? params['type'] = this.activity_type : '';
        this.router.navigate(['tuike/discovery/list'], {
          queryParams: params
        })
      } else {
        this._message.create('error', res.message);
      }
    })
  }


  goBack() {
    let params = {};
    this.activity_type ? params['type'] = this.activity_type : '';
    this.active_page ? params['page'] = this.active_page : '';
    this.router.navigate(['tuike/discovery/list'], {
      queryParams: params
    });
  }

  cardList = [];
  cardListObj = {};

  getCardList(e?) {
    let controls = this.validateForm.controls;
    if (e) {
      if (!controls['validity_start'].value || !controls['validity_end'].value) {
        this._message.create('error', '请先选择开始时间以及结束时间');
        return;
      }
      let start = moment(controls['validity_start'].value).format('YYYY:MM:DD HH:mm:ss');
      let end = moment(controls['validity_end'].value).format('YYYY:MM:DD HH:mm:ss');
      let url = `${adSystemApiUrl}/v1/admin/coupon/card_coupons_all?validity_start=${start}&validity_end=${end}`;
      if (this.cardList.length === 0) {
        this.httpService.httpGetAuth(url).subscribe(res => {
          if (res.code === 200) {
            let data = res.data;
            let flag = false;
            this.cardList = data.map(item => {
              let json = {
                label: item.card_coupons_name + "(" + (item.merchants_name) + ")",
                value: item.card_coupons_uuid,
                app_key: item.app_key,
                merchants_id: item.merchants_id,
              };
              this.cardListObj[item.card_coupons_uuid] = json;
              if (item.card_coupons_uuid == this.validateForm.controls['card_coupons_uuid'].value) {
                flag = true;
              }
              return json;
            });
            if (!flag) {
              this.validateForm.controls['card_coupons_uuid'].patchValue(null);
            }
          }
        });
      }
    }
  }

  descError = false;

  _submitForm() {
    if (this.submitStatus) {
      return;
    }
    let controls = this.validateForm.controls;
    for (const i in controls) {
      controls[i].markAsDirty();
    }

    let flag = true;
    // this.editorlist['_results'].map((e, i) => {
    //   let desc = e.clickHandle();
    //   if (desc == "<p><br></p>") {
    //     this.editors[i]['descError'] = true;
    //     flag = false;
    //   } else {
    //     this.editors[i]['descError'] = false;
    //   }
    // });

    if (this.validateForm.valid && flag) {
      this.submitStatus = true;
    } else {
      return false;
    }
    let url = `${tuikeSystemUrl}/api/v1/admin/activity_find/create?`;
    let validity_start = moment(controls["validity_start"].value).format('YYYY-MM-DD HH:mm:ss');
    let validity_end = moment(controls["validity_end"].value).format('YYYY-MM-DD HH:mm:ss');
    let title = controls['title'].value;
    let is_top = controls['is_top'].value;
    let status = controls['status'].value;
    let type = this.activity_type;
    let json = {
      validity_start,
      validity_end,
      title,
      is_top,
      status,
      type,
      show_at: '',
      pic_url: "",
      id: "",
      user_num_limit: "",
      card_coupons_uuid: "",
      category_id: "",
      app_key: "",
      merchant_id: ""
    };

    let content = [];
    this.editorlist['_results'].map((e, i) => {
      let desc = e.clickHandle();
      let link_task = [];
      this.editors[i]['checkedGoodsInfo'].map((e, i) => {
        link_task.push(e.id);
      });
      content.push({
        'content': desc,
        'link_task': link_task.join(',')
      })
    });
    json['content'] = JSON.stringify(content);

    if (this.activity_type == 3) {
      let list = this.cardListObj;
      json.user_num_limit = controls['user_num_limit'].value;
      json.show_at = moment(controls['show_at'].value).format('YYYY:MM:DD HH:mm:ss');
      let item = list[controls['card_coupons_uuid'].value];
      json.card_coupons_uuid = item ? item.value : '';
      json.app_key = item ? item.app_key : '';
      json.merchant_id = item ? item.merchants_id : '';
      delete json.category_id;
    } else if (this.activity_type == 4) {
      json.category_id = controls['category_id'].value;
      delete json.user_num_limit;
      delete json.card_coupons_uuid;
      delete json.app_key;
      delete json.merchant_id;
      delete json.show_at;
    } else if (this.activity_type == 5) {
      json.show_at = moment(controls['show_at'].value).format('YYYY:MM:DD HH:mm:ss');
      delete json.user_num_limit;
      delete json.card_coupons_uuid;
      delete json.app_key;
      delete json.merchant_id;
      delete json.category_id;
    } else {
      delete json.user_num_limit;
      delete json.card_coupons_uuid;
      delete json.category_id;
      delete json.app_key;
      delete json.merchant_id;
      delete json.show_at;
    }
    let pic_url_arr = controls['pic_url'].value;

    if (!pic_url_arr[0].url) {
      this.adOssUploadService.getSignature2(`/api/v1/common/upload`, '/v1/member/discovery/edit', pic_url_arr[0], null)
        .subscribe(res => {
            if (res.code === 200) {
              json.pic_url = res.data[0];
              this.saveDiscovery(json);
            } else {
              this._message.create('error', res.message);
              this.submitStatus = false;
            }
          }
        );
    } else {
      json.pic_url = pic_url_arr[0].url;
      this.saveDiscovery(json);
    }
  }
}
